<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8">
        <title>文章管理</title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="/static/admin/component/elementui/index.min.css">
        <link rel="stylesheet" href="/static/admin/component/toastui-editor/toastui-editor.min.css">
        <style>
            .elform-editor .el-form-item__content {
                margin-left: 0 !important;
            }
        </style>
    </head>

    <body>
        <div id="app" style="padding: 16px;">
            <div class="layui-card">
                <div class="layui-card-body">
                    <!-- element表格 -->
                    <el-row style="margin-top: 15px;">
                        <el-button @click="deleteArticleBatch" type="danger" size="small"
                            style="margin-bottom: 5px;">批量删除</el-button>
                        <el-table :data="tableData" border style="width: 100%"
                            @selection-change="handleSelectionChange">
                            <el-table-column align="center" type="selection" width="50">
                            </el-table-column>
                            <el-table-column align="center" prop="id" label="ID" width="80">
                            </el-table-column>
                            <el-table-column :fit="true" align="center" prop="title" label="标题">
                            </el-table-column>
                            <el-table-column align="center" prop="cate_name" label="分类" width="100">
                            </el-table-column>
                            <el-table-column align="center" prop="istop" label="置顶" width="80">
                                <template slot-scope="scope">
                                    <span v-text="scope.row.istop == 1 ? '是' : '否'"></span>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" prop="description" label="描述" width="300"
                                :show-overflow-tooltip="true">
                            </el-table-column>
                            <el-table-column align="center" prop="created_at" label="创建时间" width="200">
                            </el-table-column>

                            <!-- 文章内容(隐藏) -->
                            <el-table-column align="center" prop="content" label="内容" width="0" v-if="false">
                            </el-table-column>
                            <!-- 更新时间(隐藏) -->
                            <el-table-column align="center" prop="updated_at" label="更新时间" width="0" v-if="false">
                            </el-table-column>

                            <el-table-column align="center" fixed="right" label="操作" width="100">
                                <template slot-scope="scope">
                                    <el-button type="text" size="small" @click="showEditModal(scope.row)">编辑</el-button>
                                    <el-button type="text" size="small" style="color: red;"
                                        @click="deleteArticle(scope.row.id)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <el-pagination background layout="prev, pager, next" :page-sizes="[20, 30, 40, 50]"
                            :page-size="pageSize" :current-page="currentPage" :total="artTotalCount"
                            @current-change="onPageChange" @size-change="onPageSizeChange" style="margin-top: 15px">
                        </el-pagination>
                    </el-row>

                    <!-- 编辑文章表单对话框 -->
                    <el-dialog title="编辑" width="65%" :visible.sync="editFormVisible" :modal="false"
                     :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true">
                        <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="80px">
                            <!-- 文章标题 -->
                            <el-form-item label="文章标题" prop="title">
                                <el-input v-model="editForm.title" clearable></el-input>
                            </el-form-item>
                            <!-- 文章分类 -->
                            <el-form-item label="文章分类" prop="cate_name">
                                <el-select v-model="editForm.cate_name" clearable placeholder="请选择分类">
                                    <el-option v-for="cate in cateList" :key="cate.id" :label="cate.name"
                                        :value="cate.name">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <!-- 文章描述 -->
                            <el-form-item label="文章描述" prop="description">
                                <el-input type="textarea" :rows="2" v-model="editForm.description" clearable></el-input>
                            </el-form-item>
                            <!-- 是否置顶 -->
                            <el-form-item label="是否置顶" prop="istop">
                                <el-switch v-model="editForm.istop" :active-value="1" :inactive-value="0"></el-switch>
                            </el-form-item>
                            <!-- 文章内容 -->
                            <el-form-item class="elform-editor" :label-width="0">
                                <div ref="editor" id="content-editor"></div>
                            </el-form-item>
                        </el-form>

                        <div slot="footer" class="dialog-footer">
                            <el-button size="small" @click="editFormVisible = false">取消</el-button>
                            <el-button size="small" type="primary" @click="publishArticle()">确定</el-button>
                        </div>
                    </el-dialog>

                </div>
            </div>
        </div>



        <script src="/static/admin/component/elementui/vue.min.js"></script>
        <script src="/static/admin/component/elementui/index.min.js"></script>

        <script src="/static/admin/component/toastui-editor/toastui-editor-all.min.js"></script>
        <script src="/static/admin/component/toastui-editor/zh-cn.js"></script>

        <script type="text/javascript">
            new Vue({
                el: '#app',
                data: {
                    // 多选框选中数据
                    multipleSelection: [],
                    // 文章列表数据
                    tableData: [],
                    // 文章总数
                    artTotalCount: 0,
                    // 当前页码
                    currentPage: 1,
                    // 每页显示条数
                    pageSize: 20,
                    // 编辑文章表单是否显示
                    editFormVisible: false,
                    // 分类列表
                    cateList: [],
                    // 编辑文章表单
                    editForm: {
                        id: 0,
                        title: '',
                        cate_name: '',
                        description: '',
                        content: '',
                        istop: 0,
                        updated_at: '',
                    },
                    // 编辑文章表单验证规则
                    editFormRules: {
                        title: [
                            { required: true, message: '请输入文章标题', trigger: 'blur' },
                        ],
                        cate_name: [
                            { required: true, message: '请选择分类', trigger: 'change' }
                        ],
                        description: [
                            { required: true, message: '请输入文章描述', trigger: 'blur' }
                        ],
                    },
                    // markdown编辑器实例
                    editor: null,
                },
                methods: {
                    // 批量删除文章
                    deleteArticleBatch() {
                        if (!this.multipleSelection || this.multipleSelection.length === 0) {
                            return this.$message.warning('请选择要删除的文章');
                        }

                        this.$confirm('确定删除选中的文章吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            let ids = [];
                            this.multipleSelection.forEach(item => {
                                ids.push(item.id);
                            });

                            // 提交批量删除
                            fetch("/admin/article/batchDelete", {
                                method: "POST",
                                headers: {
                                    "Accept": 'application/json',
                                    "Authorization": sessionStorage.getItem('token') || '',
                                    "Content-Type": 'application/json;charset=UTF-8'
                                },
                                body: JSON.stringify({
                                    ids: ids,
                                }),
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error(res.msg);
                                    }

                                    this.$message.success('操作成功!');
                                    // 重新加载列表
                                    this.getArticleList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });

                        })
                    },

                    // 多选框选择事件
                    handleSelectionChange(val) {
                        this.multipleSelection = val;
                    },


                    // 行删除文章
                    deleteArticle(id) {
                        this.$confirm('确定删除该文章吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            // 提交删除
                            fetch(`/admin/article/delete/${id}`, {
                                method: "DELETE",
                                headers: {
                                    "Accept": 'application/json',
                                    "Authorization": sessionStorage.getItem('token') || '',
                                }
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error(res.msg);
                                    }

                                    this.$message.success('操作成功!');
                                    // 重新加载列表
                                    this.getArticleList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });
                        })
                    },

                    // 每页显示条数改变
                    onPageSizeChange(pageSize) {
                        this.pageSize = pageSize;
                        this.onPageChange(this.currentPage);
                    },

                    // 翻页
                    onPageChange(pageNum) {
                        this.currentPage = pageNum; // 更新当前页码
                        fetch(`/admin/article/list?page_num=${pageNum}&page_size=${this.pageSize}`, {
                            method: "GET",
                            headers: {
                                "Authorization": sessionStorage.getItem('token') || '',
                            },
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error(res.msg);
                                }

                                this.tableData = res.data;
                                this.artTotalCount = res.total;
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    },

                    // 显示编辑文章弹窗
                    showEditModal(row) {
                        this.editForm = row;
                        this.editFormVisible = true;

                        this.$nextTick(function () {
                            this.editor = new window.toastui.Editor({
                                el: document.getElementById('content-editor'),
                                // el: this.$refs['editor'],
                                height: '520px',
                                initialValue: row.content,
                                language: 'zh-CN',  // 设置语言为中文
                                initialEditType: 'markdown',    // 设置编辑器初始模式为Markdown
                                previewStyle: 'vertical',   // 设置预览样式为垂直
                                usageStatistics: false, // 禁用统计数据
                                previewHighlight: true, // 启用高亮
                            });
                            
                        });

                    },

                    // 提交编辑文章
                    publishArticle() {
                        // 表单验证
                        this.$refs.editForm.validate(valid => {
                            if (!valid) {   // 表单验证不通过
                                return this.$message.warning('请填写完整！');
                            }
                            if (this.editor.getMarkdown() == '') {
                                return this.$message.warning('文章内容不能为空！');
                            }

                            this.editForm.content = this.editor.getMarkdown();
                            this.editForm.updated_at = getNowTimeStr();


                            fetch(`/admin/article/edit/${this.editForm.id}`, {
                                method: "PUT",
                                headers: {
                                    "Accept": "application/json",
                                    "Content-Type": "application/json;charset=UTF-8",
                                    "Authorization": sessionStorage.getItem('token') || '',
                                },
                                body: JSON.stringify(this.editForm),
                            })
                                .then((response) => response.json())
                                .then(res => {
                                    if (res.code != 200) {
                                        return this.$message.error('操作失败！');
                                    }

                                    this.$message.success('操作成功！');
                                    this.editFormVisible = false;
                                    // 重新加载列表数据
                                    this.getArticleList();
                                })
                                .catch((err) => {
                                    console.error("Error:", err);
                                });
                        });
                    },


                    // 获取文章列表
                    getArticleList() {
                        fetch(`/admin/article/list?page_num=1&page_size=20`, {
                            method: "GET",
                            headers: {
                                "Accept": 'application/json',
                                "Authorization": sessionStorage.getItem('token') || '',
                            },
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error(res.msg);
                                }

                                this.tableData = res.data;
                                this.artTotalCount = res.total;
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    },
                    // 获取分类列表
                    getCategoryList() {
                        // 获取分类列表
                        fetch("/cate/list", {
                            method: "GET",
                            headers: {
                                "Accept": "application/json",
                                "Authorization": sessionStorage.getItem('token') || '',
                            },
                        })
                            .then((response) => response.json())
                            .then(res => {
                                if (res.code != 200) {
                                    return this.$message.error('获取数据失败');
                                }

                                this.cateList = res.data;
                            })
                            .catch((err) => {
                                console.error("Error:", err);
                            });
                    },
                },
                mounted() {
                    // 获取文章列表
                    this.getArticleList();
                    // 获取分类列表
                    this.getCategoryList();
                    
                }
            });


            // 获取当前时间字符串
            function getNowTimeStr() {
                let now = new Date();
                let year = now.getFullYear();
                let month = now.getMonth() + 1;
                let day = now.getDate();
                let hour = now.getHours();
                let minute = now.getMinutes();
                let second = now.getSeconds();

                let datetimeStr = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
                return datetimeStr;
            }
        </script>
    </body>

</html>